<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input v-model="listQuery.name" placeholder="分组名" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter" />
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                查询
            </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                @click="handleCreate">
                建群
            </el-button>
        </div>
        <el-table :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row
            style="width: 100%;" @sort-change="sortChange">
            <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80"
                :class-name="getSortClass('id')">
                <template slot-scope="{row}">
                    <span>{{ row.id }}</span>
                </template>
            </el-table-column>
            <el-table-column label="群名称" width="150px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.qname }}</span>
                </template>
            </el-table-column>
            <el-table-column label="账号" width="150px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.phone }}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column label="建群个数" width="100px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.qnum }}</span>
                </template>
            </el-table-column> -->
            <el-table-column label="每群好友数" width="100px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.qhynum }}</span>
                </template>
            </el-table-column>
            <!-- <el-table-column label="间隔数" width="100px" align="center">
                <template slot-scope="{row}">
                    <span>{{ row.jgnum }}</span>
                </template>
            </el-table-column> -->
            <el-table-column label="创建时间" width="160px" align="center">
                <template slot-scope="{row}">
                    <el-tag>{{ row.times | parseTime('{y}-{m}-{d} {h}:{i}') }} </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="群状态" class-name="status-col" width="100">
                <template slot-scope="{row}">
                    <el-tag :type="row.status | statusFilter">
                        {{ row.status == 1 ? '待创建' : row.status == 2 ? '正常' : '异常' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="状态" class-name="status-col" width="100">
                <template slot-scope="{row}">
                    <el-tag :type="row.status | statusFilter">
                        {{ row.status == 1 ? '待创建' : row.status == 2 ? '正常' : '异常' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
                <template slot-scope="{row,$index}">
                    <el-button type="primary" v-if="row.status == 1" size="mini" @click="handleUpdate(row)">
                        编辑
                    </el-button>
                    <el-button type="primary" v-if="row.status != 1" size="mini" @click="handleFetchPv(row)">
                        任务日志
                    </el-button>
                    <el-button size="mini" v-if="row.status == 1" type="danger" @click="handleDelete(row, $index)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
            @pagination="getList" />
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="90px"
                style="width: 600px; margin-left:50px;">
                <el-form-item label="群名称" prop="qname">
                    <el-input v-model="temp.qname" type="textarea" :rows="4" />
                </el-form-item>
                <el-form-item label="建群账号" prop="username">
                    <el-select v-model="temp.phone" placeholder="请选择">
                        <el-option v-for="item in zhlist" :key="item.id" :label="item.phone" :value="item.phone"
                            value-key="phone"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="建群类型">
                    <el-radio-group v-model="temp.lxtype">
                        <el-radio :label="1">普通建群</el-radio>
                        <!-- <el-radio :label="2">批量建群</el-radio> -->
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="群数量" prop="qnum" v-if="temp.lxtype == 2">
                    <el-input v-model="temp.qnum" />
                </el-form-item>
                <el-form-item label="群间隔" prop="jgnum" v-if="temp.lxtype == 2">
                    <el-input v-model="temp.jgnum" />
                </el-form-item>
                <el-form-item label="群好友数" prop="qhynum" v-if="temp.lxtype == 2">
                    <el-input v-model="temp.qhynum" />
                </el-form-item>
                <el-form-item label="建群分组" prop="zid">
                    <el-select v-model="temp.zid" class="filter-item" placeholder="请选择分组">
                        <el-option v-for="item in fzlist" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-select v-model="temp.status" class="filter-item" placeholder="Please select">
                        <el-option v-for="item in statusOptions" :key="item.key" :label="item.display_name"
                            :value="item.key" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                    取消
                </el-button>
                <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
                    创建
                </el-button>
            </div>
        </el-dialog>

        <el-dialog :visible.sync="dialogPvVisible" :title="textMap[dialogStatus]">
            <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
                <el-table-column prop="phone" label="账号" />
                <el-table-column prop="content" label="操作" />
                <el-table-column prop="jsonall" label="json数据" />
                <el-table-column label="时间" width="150px" align="center">
                    <template slot-scope="{row}">
                        <span>{{ row.times | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>

<script>
import { fetchList, fetfzlist, fetchsmslist, createArticle, updateArticle, getDel, rwlog, getzhlist } from '@/api/addqz'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

const statusOptions = [
    { key: 1, display_name: '正常' },
    { key: 2, display_name: '暂停' },
    { key: 3, display_name: '封禁' },
    { key: 4, display_name: '异常' }
]

export default {
    name: 'ComplexTable',
    components: { Pagination },
    directives: { waves },
    filters: {
        statusFilter(status) {
            const statusMap = {
                1: 'success',
                2: 'info',
                3: 'danger'
            }
            return statusMap[status]
        },
        typeFilter(type) {
            return calendarTypeKeyValue[type]
        }
    },
    data() {
        return {
            tableKey: 0,
            list: null,
            total: 0,
            listLoading: true,
            listQuery: {
                page: 1,
                limit: 20,
                // lxtype: 2,
                name: '',
            },
            statusOptions,
            showReviewer: false,
            temp: {
                id: undefined,
                qname: '',
                phone: '',
                zid: '',
                lxtype: 1,
                qhynum: '',
                jgnum: '',
                qnum: '',
                status: 1
            },
            dialogFormVisible: false,
            dialogStatus: '',
            textMap: {
                update: 'Edit',
                create: 'Create'
            },
            dialogPvVisible: false,
            smslist: [],
            fzlist: [],
            pvData: [],
            zhlist: [],
            rules: {
                qname: [{ required: true, message: '请输入群名称', trigger: 'change' }],
                zid: [{ required: true, message: '请选择建群分组', trigger: 'blur' }],
                qhynum: [{ required: true, message: '请输入群人数', trigger: 'blur' }],
                jgnum: [{ required: true, message: '请输入间隔数', trigger: 'blur' }],
                qnum: [{ required: true, message: '请输入群个数', trigger: 'blur' }],
                status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
            },
            downloadLoading: false
        }
    },
    created() {
        this.getList()
        this.getsmslist()
        this.getfzlist()
        this.getzhlist()
    },
    methods: {
        getzhlist() {
            let temp = {
                logonstatus: 2
            }
            getzhlist(temp).then(response => {
                this.zhlist = response.data.list
            })
        },
        getsmslist() {
            fetchsmslist({ logonstatus: 2 }).then(response => {
                this.smslist = response.data.list
            })
        },
        getfzlist() {
            fetfzlist().then(response => {
                this.fzlist = response.data.list
            })
        },
        getList() {
            this.listLoading = true
            fetchList(this.listQuery).then(response => {
                console.log(response.data)
                this.list = response.data.list
                this.total = response.data.count
                setTimeout(() => {
                    this.listLoading = false
                }, 1.5 * 1000)
            })
        },
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        handleModifyStatus(row, status) {
            this.$message({
                message: '操作Success',
                type: 'success'
            })
            row.status = status
        },
        sortChange(data) {
            const { prop, order } = data
            if (prop === 'id') {
                this.sortByID(order)
            }
        },
        sortByID(order) {
            if (order === 'ascending') {
                this.listQuery.sort = '+id'
            } else {
                this.listQuery.sort = '-id'
            }
            this.handleFilter()
        },
        resetTemp() {
            this.temp = {
                id: undefined,
                qname: '',
                phone: '',
                zid: '',
                lxtype: 1,
                qhynum: '',
                jgnum: '',
                qnum: '',
                status: 1
            }
        },
        handleCreate() {
            this.resetTemp()
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        createData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    createArticle(this.temp).then(() => {
                        this.dialogFormVisible = false
                        this.$notify({
                            title: 'Success',
                            message: 'Created Successfully',
                            type: 'success',
                            duration: 2000
                        })
                        this.getList();
                    })
                }
            })
        },
        handleUpdate(row) {
            this.temp = Object.assign({}, row) // copy obj
            this.dialogStatus = 'update'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        updateData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    const tempData = Object.assign({}, this.temp)
                    updateArticle(tempData).then(() => {
                        const index = this.list.findIndex(v => v.id === this.temp.id)
                        this.list.splice(index, 1, this.temp)
                        this.dialogFormVisible = false
                        this.$notify({
                            title: 'Success',
                            message: 'Update Successfully',
                            type: 'success',
                            duration: 2000
                        })
                    })
                }
            })
        },
        handleDelete(row, index) {
            let temp = {
                id: row.id
            }
            getDel(temp).then(() => {
                this.$notify({
                    title: 'Success',
                    message: 'Created Successfully',
                    type: 'success',
                    duration: 2000
                })
            })
            this.list.splice(index, 1)
        },
        handleFetchPv(row) {
            rwlog({ id: row.id }).then(response => {
                this.pvData = response.data
                this.dialogPvVisible = true
            })
        },
        handleDownload() {
            this.downloadLoading = true
            import('@/vendor/Export2Excel').then(excel => {
                const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
                const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
                const data = this.formatJson(filterVal)
                excel.export_json_to_excel({
                    header: tHeader,
                    data,
                    filename: 'table-list'
                })
                this.downloadLoading = false
            })
        },
        formatJson(filterVal) {
            return this.list.map(v => filterVal.map(j => {
                if (j === 'timestamp') {
                    return parseTime(v[j])
                } else {
                    return v[j]
                }
            }))
        },
        getSortClass: function (key) {
            const sort = this.listQuery.sort
            return sort === `+${key}` ? 'ascending' : 'descending'
        }
    }
}
</script>
